# -*- coding: utf-8 -*-
from config.config import Config
from selenium import webdriver
from common.page import Page


class Driver:
    # Driver初始化
    @staticmethod
    def init_driver():
        driver = None
        browser = Config().data[Config().data['execute']['project_name']]['browser']
        driver_type = browser['driver_type']
        width = browser['width']
        height = browser['height']
        is_phone = browser['is_phone'] == str(True)
        is_max_windows = browser['is_max_windows'] == str(True)
        is_open_devtools = browser['is_open_devtools'] == str(True)
        chrome_options = webdriver.ChromeOptions()
        # 针对网厅开户，添加手机启动模式,启动f12调试工具
        if is_phone:
            mobile_emulation = {'deviceName': 'iPhone 6'}
            chrome_options.add_experimental_option('mobileEmulation', mobile_emulation)
        if is_open_devtools:
            chrome_options.add_argument("--auto-open-devtools-for-tabs")

        chrome_options.page_load_strategy = 'normal'  # 页面加载策略
        prefs = {"credentials_enable_service": False, "profile.password_manager_enabled": False}
        chrome_options.add_experimental_option('prefs', prefs)  # 关掉密码弹窗
        chrome_options.add_experimental_option('useAutomationExtension', False)  # 取消"Chrome正受到自动软件的控制"提示
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
        chrome_options.add_argument(
            '--ignore-certificate-errors')  # 屏蔽WebDriver启动Chrome实例时总出现的“--ignore-certificate-errors”提示

        try:
            # 谷歌浏览器
            if driver_type == 'chrome':
                # http://chromedriver.storage.googleapis.com/index.html
                driver = webdriver.Chrome(options=chrome_options)
                driver.set_window_size(width, height)

            # 火狐浏览器
            if driver_type == 'firefox':
                driver = webdriver.Firefox()
                driver.set_window_size(width, height)

            # Edge浏览器
            if driver_type == 'Edge':
                # https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#downloads
                # 下载的驱动更名为MicrosoftWebDriver
                driver = webdriver.Edge()
                driver.set_window_size(width, height)

            if is_max_windows:
                driver.maximize_window()
            else:
                driver.set_window_size(width, height)
            return driver
        except Exception as e:
            print('支持’chrome,firefox,edge' + str(e))

    @staticmethod
    def get_url(driver, url):
        # 初始化
        page = Page(driver)
        # 输入URL
        page.get(url)
        return page

    @staticmethod
    def quit(driver):
        driver.quit()
